package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.SystemDictionaryItemMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ICustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SystemDictionaryItemMapper systemDictionaryItemMapper;

    @Override
    public void delete(Long id) {
        customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Customer customer) {
        //设置销售人员为当前登录的员工
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        customer.setSeller(employee);
        customer.setInputuser(employee);
        customer.setInputTime(new Date());
        String tel = customerMapper.selectByTel(customer.getTel());
        if (tel == null) {
            customerMapper.insert(customer);
        } else {
            throw new RuntimeException("电话重复");
        }
    }

    @Override
    public Customer get(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Customer> listAll() {
        return customerMapper.selectAll();
    }

    @Override
    public void update(Customer customer) {
        customerMapper.updateByPrimaryKey(customer);
    }

    public PageInfo list(QueryObject queryObject) {
        int currentPage = queryObject.getCurrentPage();
        int pageSize = queryObject.getPageSize();
        PageHelper.startPage(currentPage, pageSize, "input_time desc");
        List<Customer> list = customerMapper.list(queryObject);
        return new PageInfo(list);
    }

    @Override
    public List<Employee> selectEmployeeByRoleSn(String... sns) {
        return customerMapper.selectEmployeeByRoleSn(sns);
    }

    @Override
    public List<SystemDictionaryItem> selectJobBysn(String job) {
        return systemDictionaryItemMapper.selectJobBysn(job);
    }

    @Override
    public String selectByTel(String tel) {
        return customerMapper.selectByTel(tel);
    }

    @Override
    public List<Customer> selectCustomer() {
        return customerMapper.selectCustomer();
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        customerMapper.updateStatus(id, status);
    }
}
